﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager
{
    public partial class AdministratorLogin : Telerik.Web.UI.RadAjaxPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                System.Web.Security.FormsAuthentication.SignOut();
                Session.Abandon();
                Response.Cookies.Clear();
            }

            if (!string.IsNullOrEmpty(Request.Params["GUID"]))
            {
                string Guid = Request.QueryString["GUID"];
                GPSTrackingDBV2.Data.CompaniesQuery companiesQuery = new GPSTrackingDBV2.Data.CompaniesQuery();
                companiesQuery.AppendEquals(GPSTrackingDBV2.Entities.CompaniesColumn.Guid, Guid);

                GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.Companies> companiesEntities = GPSTrackingDBV2.Data.DataRepository.CompaniesProvider.Find(companiesQuery);
                if (companiesEntities.Count > 0)
                {
                    int CompanyID = companiesEntities.FirstOrDefault().CompanyId;
                    Response.Cookies.Add(new HttpCookie("CompanyID", CompanyID.ToString()));
                    Response.Cookies.Add(new HttpCookie("GUID", Guid));                    

                    Logo.ImageUrl = "Template/Companies/" + companiesEntities.FirstOrDefault().Logo;
                    Logo.AlternateText = companiesEntities.FirstOrDefault().Logo;
                }
                else
                {
                    Response.Cookies.Add(new HttpCookie("CompanyID", null));
                    Logo.ImageUrl = "Template/Companies/Default.png";
                    Logo.AlternateText = "Default.png";
                }

            }
            else
            {
                Response.Cookies.Add(new HttpCookie("CompanyID", null));
                Logo.ImageUrl = "Template/Companies/Default.png";
                Logo.AlternateText = "Default.png";
            }

            Response.Cookies.Add(new HttpCookie("Logo", Logo.AlternateText));
            Response.Cookies.Add(new HttpCookie("Login", "AdministratorLogin"));
        }

        protected void btnEnter_Click(object sender, EventArgs e)
        {
            //Verificar licencia activa
            //if (Request.Params["GUID"] != null)
            //{
            //    WCFAMYXLicenseManager.WCFAMYXLicenseManagerClient WCFAMYXLicenseManagerClient = new WCFAMYXLicenseManager.WCFAMYXLicenseManagerClient();
            //    if (!WCFAMYXLicenseManagerClient.License_IsActive(Request.QueryString["GUID"], 1))
            //    {
            //        showErrorMessage("La licencia del producto esta desactivada, por favor comuniquese con " + System.Configuration.ConfigurationManager.AppSettings["DesignByWww"]);
            //        return;
            //    }
            //}
            

           
            if (!string.IsNullOrEmpty(txtUsername.Text) && !string.IsNullOrEmpty(txtPassword.Text))
            {
                GPSTrackingDBV2.Entities.Administrators AdministratorEntity;
                int CompanyID;
                string AdminUsername;
                
                if (Request.Params["GUID"] != null)
                {
                    AdminUsername = txtUsername.Text;
                    CompanyID = Convert.ToInt32(Request.Cookies["CompanyID"].Value);
                    AdministratorEntity = GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.GetByAdminUsernameCompanyId(AdminUsername, CompanyID);

                    if (AdministratorEntity != null)
                    {
                        string pwd = EncryptaionManager.EncryptionManager.Encrypt(txtPassword.Text, new System.Security.Cryptography.SHA256CryptoServiceProvider());
                        if (AdministratorEntity.Password == pwd && AdministratorEntity.IsActive)
                        {
                            System.Web.Security.FormsAuthentication.SetAuthCookie(AdminUsername, false);

                            SessionManager objSessionManager = new SessionManager();
                            objSessionManager.AdminUsername = AdminUsername;
                            objSessionManager.CompanyIDSelectedComboBox = CompanyID;
                            objSessionManager.CompanyID = CompanyID;
                            objSessionManager.IsMaster = false;
                            objSessionManager.IsAdmin = true;
                            objSessionManager.IsUser = false;                            

                            HttpContext.Current.Session["SessionManager"] = objSessionManager;

                            Response.Redirect("Manager/Pages/WebDesktop.aspx");
                        }
                        else
                            showErrorMessage("La contraseña no es correcta o el administrador no esta activo");                            
                    }
                    else
                        showErrorMessage("El administrador no existe en la base de datos");                         
                }
                else
                    showErrorMessage("La compañía no ha sido definida.");                     
            }
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Compañías...');", true);
        }
    }
}